<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Config as ConfigModel;
use app\api\controller\Notify;
use app\api\common\AppPay;
use app\api\common\WxPay;
use think\Validate;
use think\Db;

class Business extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 缴费套餐
     * @ApiMethod (POST)
     * @path api/business/certificationFee
     */
    public function certificationFee()
    {
        $where = "id > 0";
        $field = "id,month,price,yhdescript,descript";
        $order = "month ASC";
        $list = Db::name("certification")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /**
     * 个人认证-商家
     * @ApiMethod (POST)
     * @path api/business/personalAuthentication
     */
    public function personalAuthentication()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        if(!isset($params["is_real"]) || empty($params["is_real"])){
            $this->error("缺少参数is_real");
        }
        $data = [
            'contact_name'=>$params["contact_name"], //联系人姓名
            'contact_tel'=>$params["contact_tel"], //电话
            'address'=>$params["address"], //所在地
            'zhuying'=>$params["zhuying"], //主营内容
            'id_card1_image'=>$params["id_card1_image"], //身份证正面
            'id_card2_image'=>$params["id_card2_image"], //身份证反面
            'hand_card_image'=>$params["hand_card_image"], //手持身份证照片
            'wx_image'=>$params["hand_card_image"], //微信二维码
        ];

        $role = [
            'contact_name' => 'require|max:5',
            'contact_tel' => 'require|regex:/^1\d{10}$/',
            'address' => 'require',
            'zhuying'=>'require',
            'id_card1_image'=>'require',
            'id_card2_image'=>'require',
            'hand_card_image'=>'require',
            'wx_image'=>'require',
        ];

        $msg = [
            'contact_name.require'=>'联系人姓名不能为空',
            'contact_name.max'=>'联系人姓名最多5个字',
            'contact_tel.require'=>'电话不能为空',
            'contact_tel.regex'=>'手机号码格式错误',
            'address.require'=>'所在地不能为空',
            'zhuying.require'=>'主营内容不能为空',
            'id_card1_image.require'=>'请上传身份证正面',
            'id_card2_image.require'=>'请上传身份证反面',
            'hand_card_image.require'=>'请上传手持身份证照片',
            'wx_image.require'=>'请上传微信二维码',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        //更新user表数据  //少交保证金的逻辑
        $user->name = $params["contact_name"];
        $user->contact_name = $params["contact_name"];
        $user->contact_tel = $params["contact_tel"];
        $user->address = $params["address"];
        $user->zhuying = $params["zhuying"];
        $user->id_card1_image = parse_url($params["id_card1_image"])["path"];
        $user->id_card2_image = parse_url($params["id_card2_image"])["path"];
        $user->hand_card_image = parse_url($params["hand_card_image"])["path"];
        $user->wx_image = parse_url($params["wx_image"])["path"];
        $user->authen_type = 1;
        $user->authen = 1;
        $user->add_authen_time = time();
        $user->deposit_price = 0;
        $user->save();
        if($params['is_real'] == 1){
            if(!isset($params["certification_id"]) || empty($params["certification_id"])){
                $this->error("缴费认证ID不能为空");
            }
            $info = Db::name("certification")->where("id",$params["certification_id"])->find();
            if(!$info){
                $this->error("缴费认证信息错误");
            }
        }
        $order_no = order_no("R");
        if($params['is_real'] == 1){
            $certification_data = [];
            $certification_data["user_id"] = $user_id;
            $certification_data["price"] = $info["price"];
            $certification_data["order_no"] = $order_no;
            $certification_data["month"] = $info["month"];
            $certification_data["add_time"] = time();
            Db::name("user_certification")->insert($certification_data);
            if($params["duan"] == 1){
                $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','商家认证');
                return json_encode($pay_message);
            }else{
                $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','商家认证');
                return json_encode($pay_message);
            }
        }else{
            $user->authen = 2;
            $user->save();
            $this->success('认证成功,请等待审核');
        }
    }

    /**
     * 公司认证-商家
     * @ApiMethod (POST)
     * @path api/business/companyAuthentication
     */
    public function companyAuthentication()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        $data = [
            'name'=>$params["name"],
            'logo'=>$params["logo"],
            'num'=>$params["num"],
            'contact_name'=>$params["contact_name"], //联系人姓名
            'contact_tel'=>$params["contact_tel"], //电话
            'address'=>$params["address"], //所在地
            'zhuying'=>$params["zhuying"], //主营内容
            'id_card1_image'=>$params["id_card1_image"], //身份证正面
            'id_card2_image'=>$params["id_card2_image"], //身份证反面
            'hand_card_image'=>$params["hand_card_image"], //手持身份证照片
            'wx_image'=>$params["hand_card_image"], //微信二维码
            'company_image'=>$params["company_image"], //营业执照
        ];

        $role = [
            'name' => 'require',
            'logo' => 'require',
            'num' => 'require',
            'contact_name' => 'require|max:5',
            'contact_tel' => 'require|regex:/^1\d{10}$/',
            'address' => 'require',
            'zhuying'=>'require',
            'id_card1_image'=>'require',
            'id_card2_image'=>'require',
            'hand_card_image'=>'require',
            'wx_image'=>'require',
            'company_image'=>'require',
        ];

        $msg = [
            'name.require'=>'公司名称不能为空',
            'logo.require'=>'公司logo不能为空',
            'num.require'=>'纳税人识别号不能为空',
            'contact_name.require'=>'联系人姓名不能为空',
            'contact_name.max'=>'联系人姓名最多5个字',
            'contact_tel.require'=>'电话不能为空',
            'contact_tel.regex'=>'手机号码格式错误',
            'address.require'=>'所在地不能为空',
            'zhuying.require'=>'主营内容不能为空',
            'id_card1_image.require'=>'请上传身份证正面',
            'id_card2_image.require'=>'请上传身份证反面',
            'hand_card_image.require'=>'请上传手持身份证照片',
            'wx_image.require'=>'请上传微信二维码',
            'company_image.require'=>'请上传营业执照',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        //更新user表数据
        $user->name = $params["name"];
        $user->logo = parse_url($params["logo"])["path"];
        $user->num = $params["num"];
        $user->contact_name = $params["contact_name"];
        $user->contact_tel = $params["contact_tel"];
        $user->address = $params["address"];
        $user->zhuying = $params["zhuying"];
        $user->id_card1_image = parse_url($params["id_card1_image"])["path"];
        $user->id_card2_image = parse_url($params["id_card2_image"])["path"];
        $user->hand_card_image = parse_url($params["hand_card_image"])["path"];
        $user->wx_image = parse_url($params["wx_image"])["path"];
        $user->company_image = parse_url($params["company_image"])["path"];
        $user->authen_type = 2;
        $user->authen = 1;
        $user->add_authen_time = time();
        $user->deposit_price = 0;
        $user->save();
        if($params["is_real"] == 1){
            if(!isset($params["certification_id"]) || empty($params["certification_id"])){
                $this->error("缴费认证ID不能为空");
            }
            $info = Db::name("certification")->where("id",$params["certification_id"])->find();
            if(!$info){
                $this->error("缴费认证信息错误");
            }
        }
        $order_no = order_no("R");
        if($params['is_real'] == 1){
            $certification_data = [];
            $certification_data["user_id"] = $user_id;
            $certification_data["price"] = $info["price"];
            $certification_data["order_no"] = $order_no;
            $certification_data["month"] = $info["month"];
            $certification_data["add_time"] = time();
            Db::name("user_certification")->insert($certification_data);
            if($params["duan"] == 1){
                $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','商家认证');
                return json_encode($pay_message);
            }else{
                $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','商家认证');
                return json_encode($pay_message);
            }
        }else{
            $user->authen = 2;
            $user->save();
            $this->success('认证成功,请等待审核');
        }
    }

    /*
     * 缴纳保证金
     * @ApiMethod (POST)
     * @path api/business/paymentDeposit
     * */
    public function paymentDeposit()
    {
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        $deposit_price = ConfigModel::getConfigValue("deposit_price");
        $order_no = order_no("B");
        $deposit_data = [];
        $deposit_data["user_id"] = $user_id;
        $deposit_data["price"] = $deposit_price;
        $deposit_data["order_no"] = $order_no;
        $deposit_data["add_time"] = time();
        Db::name("user_deposit")->insert($deposit_data);
        if($params["duan"] == 1){
            $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','缴纳保证金');
            return json_encode($pay_message);
        }else{
            $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','缴纳保证金');
            return json_encode($pay_message);
        }
    }

    /*
     * 商家续费
     * @ApiMethod (POST)
     * @path api/business/merchantRenewal
     * */
    public function merchantRenewal()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        if(!isset($params["certification_id"]) || empty($params["certification_id"])){
            $this->error("缴费认证ID不能为空");
        }
        $info = Db::name("certification")->where("id",$params["certification_id"])->find();
        if(!$info){
            $this->error("缴费认证信息错误");
        }
        $order_no = order_no("X");
        $certification_data = [];
        $certification_data["user_id"] = $user_id;
        $certification_data["price"] = $info["price"];
        $certification_data["order_no"] = $order_no;
        $certification_data["month"] = $info["month"];
        $certification_data["add_time"] = time();
        Db::name("user_certification")->insert($certification_data);
        if($params["duan"] == 1){
            $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','商家续费');
            return json_encode($pay_message);
        }else{
            $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','商家续费');
            return json_encode($pay_message);
        }
//            $certification_data = [];
//            $certification_data["user_id"] = $user_id;
//            $certification_data["price"] = $info["price"];
//            $certification_data["order_no"] = $order_no;
//            $certification_data["month"] = $info["month"];
//            $certification_data["ispay"] = 1;
//            $certification_data["add_time"] = time();
//            $certification_data["pay_time"] = time();
//            Db::name("user_certification")->insert($certification_data);
//            $user->authen = 3;
//            if($user->end_time){
//                $end_time = strtotime($user->end_time)+($info["month"]*86400*30);
//                $user->end_time = $end_time;
//            }else{
//                $end_time = time()+($info["month"]*86400*30);
//                $user->end_time = $end_time;
//            }
//            $user->save();
//            $this->success('续费成功');

    }


    /**
     * 取消认证
     * @ApiMethod (POST)
     * @path api/business/cancelAuthentication
     */
    public function cancelAuthentication()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if($user["authen"] != '4'){
            $this->error("非拒绝状态不可取消认证");
        }
        $where = "user_id = {$user_id}";
        $where.= " AND ispay = '1'";
        $certification_info = Db::name("user_certification")->where($where)->order("id","desc")->find();
        if(!$certification_info){
            $this->error("认证缴费信息有误");
        }
//        $certification_info["price"] = 1;
        $WxPay = new WxPay();
        $res = $WxPay->Refund($certification_info['transaction_id'], $certification_info['order_no'], $certification_info["price"], $certification_info["price"],'取消认证');
        if ($res['code'] == 1) {
            $user->authen = 1;
            $user->save();
            $this->success('取消认证成功');
        }else{
            $this->success('取消认证失败');
        }
    }

    /**
     * 认证费明细
     * @ApiMethod (POST)
     * @path api/business/userCertification
     */
    public function userCertification()
    {
        $user_id = $this->auth->user_id;
        $where = "user_id = {$user_id}";
        $where.= " AND ispay = '1'";
        $field = "id,price,month,istui,reason,pay_time,authen_time";
        $order = "add_time DESC";
        $list = Db::name("user_certification")->where($where)->field($field)->order($order)->select();
        foreach ($list as &$value){
            if($value['pay_time']){
                $value['pay_time'] = date("Y-m-d H:i:s",$value['pay_time']);
            }else{
                $value['pay_time'] = "";
            }
            if($value['authen_time']){
                $value['authen_time'] = date("Y-m-d H:i:s",$value['authen_time']);
            }else{
                $value['authen_time'] = "";
            }
        }
        $this->success("请求成功",$list);
    }

    /**
     * 保证金明细
     * @ApiMethod (POST)
     * @path api/business/userDeposit
     */
    public function userDeposit()
    {
        $user_id = $this->auth->user_id;
        $where = "user_id = {$user_id}";
        $where.= " AND ((ispay = '1' AND type = '1') OR (authen_tui = '2' AND type = '2'))";
        $field = "id,price,reason,type,pay_time,authen_time,authen_tui";
        $order = "add_time DESC";
        $r_where = "user_id = {$user_id}";
        $r_where.= " AND ispay = '1'";
        $info = Db::name("user_deposit")->where($r_where)->order("id","desc")->find();
        if($info){
            if($info["authen_tui"] == '3'){
                $reason = $info["reason"];
            }else{
                $reason = "";
            }
        }else{
            $reason = "";
        }
        $t_where = "user_id = {$user_id}";
        $t_where.= " AND ispay = '1'";
        $t_where.= " AND type = '2'";
        $is_tui = Db::name("user_deposit")->where($t_where)->order("id","desc")->value("authen_tui");
        $list = Db::name("user_deposit")->where($where)->field($field)->order($order)->select();
        foreach ($list as &$value){
            if($value['pay_time']){
                $value['pay_time'] = date("Y-m-d H:i:s",$value['pay_time']);
            }else{
                $value['pay_time'] = "";
            }
            if($value['authen_time']){
                $value['authen_time'] = date("Y-m-d H:i:s",$value['authen_time']);
            }else{
                $value['authen_time'] = "";
            }
        }
        $data = [
            'reason'=>empty($reason) ?"": $reason,
            'is_tui'=>empty($is_tui) ?"": $is_tui,
            'list'=>$list
        ];
        $this->success("请求成功",$data);
    }

    /**
     * 群聊保证金
     * @ApiMethod (POST)
     * @path api/business/chatGroupUser
     */
    public function chatGroupUser()
    {
        $user_id = $this->auth->user_id;
        $where = "gu.user_id = {$user_id}";
        $where.= " AND ispay = '1'";
        $field = "gu.id,cg.name,gu.price,gu.pay_time,gu.is_tui,gu.tui_price,gu.tui_time";
        $order = "gu.add_time DESC";
        $list = Db::name("chat_group_user")->alias("gu")
            ->join("chat_group cg","gu.group_id = cg.id")
            ->where($where)->field($field)->order($order)->select();
        foreach ($list as &$value){
            if($value['pay_time']){
                $value['pay_time'] = date("Y-m-d H:i:s",$value['pay_time']);
            }else{
                $value['pay_time'] = "";
            }
            if($value['tui_time']){
                $value['tui_time'] = date("Y-m-d H:i:s",$value['tui_time']);
            }else{
                $value['tui_time'] = "";
            }
        }
        $this->success("请求成功",$list);
    }

    /**
     * 申请退还保证金
     * @ApiMethod (POST)
     * @path api/business/refundDeposit
     */
    public function refundDeposit()
    {
        $user_id = $this->auth->user_id;
        //缴纳保证金信息
        $d_where = "user_id = {$user_id}";
        $d_where.= " AND ispay = '1'";
        $d_where.= " AND type = '1'";
        $deposit_info = Db::name("user_deposit")->where($d_where)->order("id","desc")->find();
        if(!$deposit_info){
            $this->error("信息错误");
        }
        $where = "user_id = {$user_id}";
        $where.= " AND ispay = '1'";
        $where.= " AND type = '2'";
        $where.= " AND authen_tui = '1'";
        $info = Db::name("user_deposit")->where($where)->find();
        if($info && $info['authen_tui'] != 3){
            $this->error("已提交申请,请勿重复提交");
        }else{
            $order_no = order_no("BT");
            $deposit_data = [];
            $deposit_data["user_id"] = $user_id;
            $deposit_data["price"] = $deposit_info['price'];
            $deposit_data["order_no"] = $deposit_info['order_no'];
            $deposit_data["transaction_id"] = $deposit_info['transaction_id'];
            $deposit_data["ispay"] = 1;
            $deposit_data["tui_order_no"] = $order_no;
            $deposit_data["pay_time"] = $deposit_info['pay_time'];
            $deposit_data["type"] = 2;
            $deposit_data["add_time"] = time();
            Db::name("user_deposit")->insert($deposit_data);
            $this->success("申请成功,请等待审核");
        }
    }

    /**
     * 滚动信息
     * @ApiMethod (POST)
     * @path api/business/rollMessage
     */
    public function rollMessage()
    {
        $where = "id > 0";
        $field = "id,name,phone,province,description";
        $list = Db::name("roll_message")->where($where)->field($field)->select();
        $this->success("请求成功",$list);
    }

}
